import axios from "axios";
import { MessageBox, Message, Loading } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import Vue from "vue";
import router from "@/router";
var loadObj = null;
let requestMath = 0;

const service = axios.create({
  baseURL: "http://125.39.77.18:9021/mall-admin",
  // baseURL: "http://175.178.247.222:8021/mall-admin",
  // baseURL: "http://tj.ss5.tunnelfrp.com/mall-admin",  //向 本地
	// baseURL: "http://192.168.1.40:8201/mall-admin",  //向 本地
  timeout: 5000,
});
service.interceptors.request.use(
  (config) => {
    requestMath++;
    if (store.state.token) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }

    loadObj = Loading.service({
      text: "",
      spinner: "el-icon-loading",
      background: "rgba(0,0,0,0.7)",
      lock: true,
    });
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    if (--requestMath == 0) {
      setTimeout(() => {
        Vue.nextTick(() => {
          if (loadObj) {
            loadObj.close();
            loadObj = null;
          }
        });
      }, 800);
    }
    const res = response.data;
    if (res.code != "200") {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      if (res.code == "401") {
        // 去登录页面
        router.push("/login");
      }

      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    if (--requestMath == 0) {
      setTimeout(() => {
        Vue.nextTick(() => {
          if (loadObj) {
            loadObj.close();
            loadObj = null;
          }
        });
      }, 800);
    }
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
